<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>{{ $t("common.filterSearch") }}</span>
        <el-button
          style="float: right"
          type="primary"
          size="small"
          @click="searchCertificateById(certificate_id)"
        >
          {{ $t("common.search") }}
        </el-button>
      </div>

      <div style="margin-top: 25px">
        <el-form :inline="true" size="small" label-width="140px">
          <el-form-item :label="$t('certificatelist.search.id')">
            <el-input
              style="width: 203px"
              v-model="certificate_id"
              :placeholder="$t('certificatelist.search.plid')"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!--导入按钮 -->
    <el-button type="primary" @click="importData">{{
      $t("common.import")
    }}</el-button>

    <!-- 导出按钮 -->

    <el-button
      type="primary"
      :loading="btnLoading"
      @click="exportData"
      style="margin-left: 10px"
    >
      {{ $t("common.export") }}</el-button
    >

    <!-- 添加证书-->
    <div align="right">
      <el-button
        icon="el-icon-thumb"
        type="primary"
        size="small"
        @click="fetchDataList"
      >
        {{ $t("certificatelist.search.fetch") }}
      </el-button>
      <el-button type="success" icon="el-icon-plus" @click="showAddDialog">
        {{ $t("common.add") }}</el-button
      >
    </div>

    <!-- 证书列表 -->
    <el-table
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        align="center"
        width="70"
        :label="$t('certificatelist.table.certificate_id')"
      >
        <template slot-scope="scope">
          {{ scope.row.certificate_id }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('certificatelist.table.name')"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('certificatelist.table.part')"
        width="90"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.part }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="$t('certificatelist.table.content')"
      >
        <template slot-scope="scope">
          {{ scope.row.content }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="80"
        :label="$t('certificatelist.table.number_target')"
      >
        <template slot-scope="scope">
          {{ scope.row.number_target }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="80"
        :label="$t('certificatelist.table.time_target')"
      >
        <template slot-scope="scope">
          {{ scope.row.time_target }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="80"
        :label="$t('certificatelist.table.score_target')"
      >
        <template slot-scope="scope">
          {{ scope.row.score_target }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="80"
        :label="$t('certificatelist.table.pay_target')"
      >
        <template slot-scope="scope">
          {{ scope.row.pay_target }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="70"
        :label="$t('certificatelist.table.like_target')"
      >
        <template slot-scope="scope">
          {{ scope.row.like_target }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="80"
        :label="$t('certificatelist.table.collect_target')"
      >
        <template slot-scope="scope">
          {{ scope.row.collect_target }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('certificatelist.table.create_time')"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          {{ dateFormat(scope.row.create_time) }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('common.operate')"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editCertificate(scope.row)"
          >
            {{ $t("common.update") }}
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="delCertificate(scope.row.certificate_id)"
          >
            {{ $t("common.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 导入 -->
    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
          <el-upload
            :action="'http://42.194.159.131:8080/certificate/user/batchAdd'"
            :headers="headers"
            :on-success="onUploadSuccess"
            :multiple="false"
            class="upload-demo"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传excel文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <div class="block" style="float: right; margin-top: 20px">
      <!-- <span class="demonstration">显示总数</span> -->
      <el-pagination
        background
        @current-change="fetchDataList"
        :current-page.sync="page_num"
        :page-size="page_size"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>

      <!-- 对话框 -->
      <el-dialog
        :title="
          certificate_form.certificate_id ? '修改证书信息' : '添加证书信息'
        "
        :visible.sync="dialogFormVisible"
      >
        <el-form
          style="width: 80%"
          :model="certificate_form"
          :rules="rules"
          ref="ruleForm"
        >
          <el-form-item label="证书名称：" label-width="120px" prop="name">
            <el-input
              autocomplete="off"
              v-model="certificate_form.name"
            ></el-input>
          </el-form-item>

          <el-form-item label="所属模块：" label-width="120px" prop="part">
            <el-select
              v-model="certificate_form.part"
              placeholder="请选择证书所属模块"
              style="width: 390px"
            >
              <el-option label="全模块" value="全模块"></el-option>
              <el-option label="健康课程" value="健康课程"></el-option>
              <el-option label="问答考试" value="问答考试"></el-option>
              <el-option label="健康商城" value="健康商城"></el-option>
              <el-option label="健康知识" value="健康知识"></el-option>
              <el-option label="健康问答" value="健康问答"></el-option>
              <el-option label="健康管理" value="健康管理"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="证书内容：" label-width="120px" prop="content">
            <el-input
              type="textarea"
              v-model="certificate_form.content"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="数量目标："
            label-width="120px"
            prop="number_target"
          >
            <el-input
              autocomplete="off"
              v-model.number="certificate_form.number_target"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="时间目标："
            label-width="120px"
            prop="time_target"
          >
            <el-input
              autocomplete="off"
              v-model.number="certificate_form.time_target"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="分数目标："
            label-width="120px"
            prop="score_target"
          >
            <el-input
              autocomplete="off"
              v-model.number="certificate_form.score_target"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="消费目标："
            label-width="120px"
            prop="pay_target"
          >
            <el-input
              autocomplete="off"
              v-model.number="certificate_form.pay_target"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="点赞个数目标："
            label-width="120px"
            prop="like_target"
          >
            <el-input
              autocomplete="off"
              v-model.number="certificate_form.like_target"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="收藏个数目标："
            label-width="120px"
            prop="collect_target"
          >
            <el-input
              autocomplete="off"
              v-model.number="certificate_form.collect_target"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrEditCertificate"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import certificate from "@/api/certificatemanage";
export default {
  name: "certificatelist",
  data() {
    return {
      certificate_id: "",
      list: [], //列表条件封装对象
      page_num: 1,
      page_size: 8, //每8个数据一页
      total: 1, //初始化
      dialogFormVisible: false, //对话框（查看）
      dialogImportVisible: false, //弹框
      certificate_form: {},
      btnLoading: false,
      headers: {
        Authorization: getToken(),
      },
      rules: {
        name: [
          { required: true, message: "请输入内容", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        part: [
          { required: true, message: "请输入模块", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请输入内容", trigger: "blur" },
          {
            min: 2,
            max: 100,
            message: "长度在 2 到 100 个字符",
            trigger: "blur",
          },
        ],
        number_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        time_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        score_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        pay_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        like_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
        collect_target: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "请输入数字值", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.fetchDataList();
  },
  methods: {
    dateFormat: function (time) {
      var date = new Date(time);
      var year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
    //渲染所有证书列表
    fetchDataList() {
      var vm = this;
      certificate
        .getCertificateList(this.page_num, this.page_size)
        .then((res) => {
          // console.log(res)
          vm.list = res.data.certificate.list;
          vm.total = res.data.certificate.total;
        })
        .catch((error) => {
          vm.$message.error("error");
          console.log(error);
        });
    },
    //添加证书显示
    showAddDialog() {
      this.dialogFormVisible = true;
      this.certificate_form = {};
    },
    //编辑证书显示
    editCertificate(row) {
      // console.log(row);
      this.dialogFormVisible = true;
      this.certificate_form = { ...row };
    },
    //添加/编辑证书
    addOrEditCertificate() {
      this.$refs.ruleForm.validate(async (success) => {
        //如果全部字段符合条件
        if (success) {
          this.dialogFormVisible = false;
          let result = await certificate.addOrEditCertificate(
            this.certificate_form
          );
          if (result.errorCode == 0) {
            this.$message({
              type: "success",
              message: this.certificate_form.certificate_id
                ? "修改证书信息成功"
                : "添加证书信息成功",
            });
            this.fetchDataList();
          }
        } else {
          vm.$message.error("error");
          console.log(error);
        }
      });
    },
    //删除证书
    delCertificate(certificate_id) {
      // console.log(certificate_id);
      this.$confirm("此操作将永久删除该证书信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          certificate.delCertificate(certificate_id).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面数据
            this.fetchDataList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //根据证书ID搜索证书
    searchCertificateById(certificate_id) {
      var vm = this;
      certificate
        .getCertificateById(this.certificate_id)
        .then((res) => {
          // console.log(res)
          if (res.errorCode == 0) {
            vm.$message({
              message: "查找成功！",
              type: "success",
            });
            var searchList = [];
            searchList.push(res.data.certificate);
            vm.list = searchList;
            vm.total = searchList.length;
            this.certificate_id = "";
          }
        })
        .catch((error) => {
          vm.$message.error("查找失败！");
          console.log(error);
        });
    },
    //导入数据
    importData() {
      this.dialogImportVisible = true;
    },
    //上传成功调用
    onUploadSuccess() {
      this.dialogImportVisible = false;
      this.fetchDataList(1);
      this.$message({
        message: "导入数据成功!",
        type: "success",
      });
    },
    //导出数据
    exportData() {
      certificate
        .exportCerData()
        .then((res) => {
          // console.log(res);
          let url = window.URL.createObjectURL(new Blob([res]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", "证书列表.xls");
          document.body.appendChild(link);
          link.click();
        })
        .catch((error) => {
          this.$message.error("下载失败");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>

